import React, { Component, Fragment } from "react";
// antd
import {Table, Button, Col, Pagination, Form, Input, Typography, Space, Tag, notification, Modal, Tooltip, Select, List} from "antd";
import Action from "@c/buttonAction/Index";
import { CopyOutlined, CheckOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
// http
import http from '../../../utils/request';

// ansi
import {CopyToClipboard} from 'react-copy-to-clipboard';

import VirtualList from 'rc-virtual-list';

const { Text } = Typography;
const { Option } = Select;

  
class Pod extends Component {
    constructor(props){
        super(props)

        this.state = {
            loading: false,
            // 分页
            total: '',
            page: 1,
            page_number: 1000,

            // 搜索
            search_common: null,
            search_namespace: null,

            pod_log: null,

            selectedRowKeys: [],

            visible_pod_log: false,

            namespace_list: [],

            pod_name: null,
            pod_ip: null,
            
            // 表格
            dataSource: [],
            columns: [
                {title: "POD", dataIndex: "pod_ip", key: "pod_ip",
                    render: (text, rowData) => {
                        return(
                            <Space direction="vertical">
                                <CopyToClipboard text={rowData.name} 
                                    onCopy={() => 
                                        this.setState({copied: true},
                                        notification.open({
                                            message: '已复制到剪贴板',
                                            icon: <CheckOutlined style={{ color: 'green' }} />,
                                            duration: 2,
                                            placement: 'top',
                                        })
                                    )}
                                >
                                    <span><span style={{marginRight: "5px"}}><CopyOutlined /></span><span style={{color: "#6587FF"}}>{rowData.name}</span></span>
                                </CopyToClipboard>
                                <Text>{rowData.pod_ip}</Text>
                                <Text>{rowData.node_ip}</Text>
                            </Space>
                        )
                    }
                },
                {title: "命名空间", dataIndex: "namespace", key: "namespace",
                    render: (text, rowData) => {
                        return (<Tag>{rowData.namespace}</Tag>)
                    }
                },
                {title: "资源类型", dataIndex: "kinds", key: "kinds",
                    render: (text, rowData) => {
                        var kind_list = []
                        rowData.kinds.map((item, index) =>(
                            kind_list.push(<Tag key={index}>{item.kind}</Tag>)
                        ))  
                        return (<div>{kind_list}</div>)
                    }
                },
                {title: "就绪", dataIndex: "status", key: "status",
                    render: (text, rowData) => {
                        var conditions_list = []
                        var conditions_text = null

                        rowData.conditions.map((item, index)=>(
                            conditions_list.push(<div key={index}>{item.key}: {item.value}</div>)
                        ))

                        if (rowData.status === "True") {
                            conditions_text = <span style={{color: "green"}}>就绪</span>
                        } else if (rowData.status === "False") {
                            conditions_text = <span style={{color: "red"}}>非就绪</span>
                        }

                        return(
                            <div>
                                <div>
                                    <Tooltip title={conditions_list}>
                                        {conditions_text} <ExclamationCircleOutlined />
                                    </Tooltip>
                                </div>
                                <div style={{marginTop: "3px"}}>
                                    {rowData.phase}
                                </div>
                                <div style={{marginTop: "3px"}}>
                                    {rowData.create_time}
                                </div>
                            </div>
                        )
                    }
                },
                // {title: "状态", dataIndex: "phase", key: "phase"},
                {title: "节点亲和性", dataIndex: "selectors", key: "selectors",
                    render: (text, rowData) => {
                        var selectors = []
                        rowData.selectors.map((item, index)=>(
                            selectors.push(<div key={index} style={{marginTop: "10px"}}><Tag>{item}</Tag></div>)
                        ))
                        return(<div>{selectors}</div>)
                    }
                },
                {title: "容器个数", dataIndex: "containers", key: "containers"},
                // {title: "创建时间", dataIndex: "create_time", key: "create_time"},
                {title: "操作", dataIndex: "operation", key: "operation", fixed: 'right',
                    render: (text, rowData) => {
                        return (
                            <div>
                                <Action.Button onClick={() => this.onPodLogBtn(rowData)}>查看日志</Action.Button>
                                <Action.Button onClick={() => this.onPodDeleteBtn(rowData)}>删除容器</Action.Button>
                            </div>
                        )
                    }
                }
            ],
        }
    }

    componentDidMount() {
        this.loadData(this.props.kubernetes_id)
        this.loadDataNamespace(this.props.kubernetes_id)
    }

    // 父组件中改变了props传值时触发的函数
    componentWillReceiveProps(nextProps) {
        if (this.props.kubernetes_id !== nextProps.kubernetes_id ) {
            this.loadData(nextProps.kubernetes_id)
            this.loadDataNamespace(nextProps.kubernetes_id)
        }
    }
    
    loadData = (kubernetes_id) => {
        this.setState({loading: true})
        const requestData = {'operation_type': 'get_pod_list', 'common': this.state.search_common, 'namespace': this.state.search_namespace}
        // 获取database列表
        http.patch('/cloud/kubernetes/node/' + kubernetes_id, requestData).then(response=>{
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false,
            })
        }).catch()
    }

    loadDataNamespace = (kubernetes_id) => {
        const requestData = {'operation_type': 'get_namespace'}
        http.patch('/cloud/kubernetes/obj/' + kubernetes_id, {params: requestData}).then(response=>{
            const namespace_list = []
            const resp_data = response.data.data
            for (let i = 0; i < resp_data.length; i++) {
                namespace_list.push(<Option key={resp_data[i]}>{resp_data[i]}</Option>)
            }
            this.setState({namespace_list: namespace_list})
        })
    }

    // 切换每页数量
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            // this.loadData()
        })
    }    

    /** 搜索 */
    onFinishSearch = (data) => {
        this.setState({
            search_namespace: data.namespace ? data.namespace : null,
            search_common: data.search_common,
            page: 1
        })
        this.loadData(this.props.kubernetes_id)
    }

    // 批量选中标签
    onSelectChange = (selectedRowKeys) => {
        this.setState({
            selectedRowKeys: selectedRowKeys
        })
    }

    // 查看POD日志
    onPodLogBtn = (rowData) => {
        this.setState({
            loading: true,
            pod_name: rowData.name,
            pod_ip: rowData.pod_ip
        })
        const requestData = {'operation_type': 'pod_log',  'pod_name': rowData.name, 'namespace': rowData.namespace}
        http.patch('/cloud/kubernetes/node/' + this.props.kubernetes_id, requestData).then(response=>{
            this.setState({
                visible_pod_log: true,
                loading: false,
                pod_log: response.data.data
            })
            // this.loadData(this.props.kubernetes_id)
        }).catch()    
    }

    // 查看POD日志取消
    onFinishPodLogCancel = () => {
        this.setState({
            visible_pod_log: false,
            pod_log: null,
            pod_name: null,
            pod_ip: null,
        })
    }

    // 删除POD
    onPodDeleteBtn = (rowData) => {
        this.setState({loading: true})
        const requestData = {'operation_type': 'pod_delete',  'pod_name': rowData.name, 'namespace': rowData.namespace}
        http.patch('/cloud/kubernetes/node/' + this.props.kubernetes_id, requestData).then(response=>{
            this.loadData(this.props.kubernetes_id)
        }).catch()
    }

    render(){
        const { loading, columns, dataSource, total, selectedRowKeys, namespace_list, pod_log, pod_name, pod_ip, visible_pod_log} = this.state
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        }

        const ContainerHeight = 600
 
        var myStyle = {margin: '20px'}
        var myStyle1 = {margin: '10px', float: 'right'}
        var myStyleForm = {marginRight: '10px', marginTop: '5px'}

        return (
            <Fragment>
                <Form layout="inline" onFinish={this.onFinishSearch} size="small">
                    <Form.Item label="搜索内容" name="search_common" style={myStyleForm}>
                        <Input placeholder="节点名称/IP/标签"  />
                    </Form.Item>

                    <Form.Item label="命名空间" name="namespace" size="small" style={myStyleForm}>
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="选择命名空间"
                        >
                            {namespace_list}
                        </Select>                      
                    </Form.Item>

                    <Form.Item shouldUpdate={true} style={myStyleForm}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>

                <div style={myStyle1}></div>

                <Table
                    size="small"
                    pagination={false} 
                    rowSelection={rowSelection} 
                    rowKey="node_name"
                    columns={columns} 
                    dataSource={dataSource}
                    loading={loading}
                    scroll={{ y: 600, x: 1500 }}
                >
                </Table>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            total={total}
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>

                <Modal
                    title={<div style={{ color: 'red' }} >{pod_name} ({pod_ip})</div>}
                    visible={visible_pod_log}  
                    onCancel={this.onFinishPodLogCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                    width={1500}                  
                    >
                    { pod_log &&
                        <List>
                            <VirtualList
                            data={pod_log}
                            height={ContainerHeight}
                            itemHeight={10}
                            itemKey="email"
                            size={10}
                            // onScroll={onScroll}
                            >
                            {(item, index) => (
                                <List.Item key={index}>
                                <List.Item.Meta
                                    avatar={<img src="https://yunwei-public.oss-cn-zhangjiakou.aliyuncs.com/ops/common/log.png" alt="logo" style={{ marginTop: "4px", height: '16px'}}/>}
                                    title={item}
                                />
                                </List.Item>
                            )}
                            </VirtualList>
                        </List>
                    }

                     


                            {/* <List
                                dataSource={pod_log}
                                renderItem={item => (
                                <List.Item key={item.email}>
                                    <List.Item.Meta description={item}/>
                                </List.Item>
                                )}
                            /> */}
                    
                </Modal>
            </Fragment>
        )
    }
}

export default Pod;